package com.dayaokeji.rhythmschoolstudent.client.mine;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.dayaokeji.imkitwrapper.init.ImKitWrapper;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseFragment;
import com.dayaokeji.rhythmschoolstudent.client.home.course.ranking.FindCourseTemplateAllActivity;
import com.dayaokeji.rhythmschoolstudent.client.main.MainFragment;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.StudentIdLoginActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.group.GroupActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.statistics.FindAttendanceStatisticsActivity;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.event.AppStateEvent;
import com.dayaokeji.rhythmschoolstudent.event.FinishMainEvent;
import com.dayaokeji.rhythmschoolstudent.event.UpdateUserInfoEvent;
import com.dayaokeji.rhythmschoolstudent.glide.GlideUrlModel;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.ServerResponseCode;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.UserInfo;
import com.othershe.library.NiceImageView;
import com.tencent.bugly.beta.Beta;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;

/**
 * 我的
 */
public class MineFragment extends BaseFragment implements MainFragment {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.iv_user_avatar)
    NiceImageView ivUserAvatar;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_job_number)
    TextView tvUserJobNumber;

    @BindView(R.id.tv_current_version)
    TextView tvCurrentVersion;
    private UserInfo userInfo;

    private static final UserApi userApi = ApiUtils.getApi(UserApi.class);
    private Call<ServerResponse<Void>> logoutCall;

    @Nullable
    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mine, container, false);
    }

    @Override
    public Toolbar getToolbar() {
        return toolbar;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @SuppressLint("SetTextI18n")
    private void initData() {
        userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            tvUserName.setText(userInfo.getName());
            tvUserJobNumber.setText(getString(R.string.student_id_str, userInfo.getWorkNo()));
            withGlide().load(new GlideUrlModel(ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId()))).into(ivUserAvatar);
        }
        tvCurrentVersion.setText("当前版本: V"+AndroidUtils.getVersionName());
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            userInfo = UserUtils.getUserInfo();
        }
        super.setUserVisibleHint(isVisibleToUser);
    }


    @OnClick({
            R.id.ll_personal_info,
            R.id.ll_group_list,
            R.id.ll_about_us,
            R.id.ll_feedback,
            R.id.ll_helper,
            R.id.ll_check_update,
            R.id.ll_statistics,
            R.id.ll_scoring_ranking,
            R.id.btn_exit_app
    })
    public void onClick(View view) {
        if (getActivity() == null) return;
        switch (view.getId()) {
            case R.id.ll_personal_info:
                startActivity(new Intent(getActivity(),PersonalInfoActivity.class));
                break;
            case R.id.ll_group_list:
                startActivity(new Intent(getActivity(), GroupActivity.class));
                break;
            case R.id.ll_about_us:
                startActivity(new Intent(getActivity(),AboutUsActivity.class));
                break;
            case R.id.ll_feedback:
                FeedbackActivity.navigation(getActivity());
                break;
            case R.id.ll_helper:
                AppHelperActivity.navigation(getActivity());
                break;
            case R.id.ll_check_update:
                Beta.checkUpgrade();
                break;
            case R.id.ll_statistics:
                startActivity(new Intent(getActivity(), FindAttendanceStatisticsActivity.class));
                break;
            case R.id.ll_scoring_ranking: // 课程排名
                FindCourseTemplateAllActivity.navigation(getActivity());
                break;
            case R.id.btn_exit_app:
                logout();
                break;
        }
    }

    /**
     * 退出
     */
    private void logout() {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("您确认要退出当前账号吗？").setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                logoutHandle();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create();
        alertDialog.show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.warring_red));
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.gray));
    }

    /**
     * 退出登录网络请求处理
     */
    private void logoutHandle() {
        EventBus.getDefault().post(new AppStateEvent(false, Constant.APP_STATE_EXIT_CODE));
        logoutCall = userApi.logout();
        logoutCall.enqueue(new ServerCallback<Void>(getActivity(),"正在退出...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                ImKitWrapper.stopImService();
                if (success) {
                    UserUtils.setUserInfo(null);
                    UserUtils.setAccessToken(null);
                    UserInfoDao.delUserInfo();
                    if (getActivity() != null) {
                        JPushInterface.setAlias(getActivity(), "", null);
                        UserUtils.stopService(getActivity());
                    }
                    ActivityStackManager.finishAll();
                    EventBus.getDefault().post(new FinishMainEvent());
                    Intent intent = new Intent(getActivity(), StudentIdLoginActivity.class);
                    startActivity(intent);
                }else{
                    if (response.getHeader() != null) {
                        int code = response.getHeader().getCode();
                        if (ServerResponseCode.INVALID_TOKEN == code) {
                            UserUtils.setUserInfo(null);
                            UserUtils.setAccessToken(null);
                            UserInfoDao.delUserInfo();
                            if (getActivity() != null) {
                                JPushInterface.setAlias(getActivity(), "", null);
                                UserUtils.stopService(getActivity());
                            }
                            ActivityStackManager.finishAll();
                            EventBus.getDefault().post(new FinishMainEvent());
                            Intent intent = new Intent(getActivity(), StudentIdLoginActivity.class);
                            startActivity(intent);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<Void>> call, Throwable t) {
                super.onFailure(call, t);
                ImKitWrapper.stopImService();
                UserUtils.setUserInfo(null);
                UserUtils.setAccessToken(null);
                UserInfoDao.delUserInfo();
                if (getActivity() != null) {
                    JPushInterface.setAlias(getActivity(), "", null);
                    UserUtils.stopService(getActivity());
                }
                ActivityStackManager.finishAll();
                EventBus.getDefault().post(new FinishMainEvent());
                if (getActivity() != null) {
                    Intent intent = new Intent(getActivity(), StudentIdLoginActivity.class);
                    startActivity(intent);
                }
            }
        });
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void update(UpdateUserInfoEvent updateUserInfo) {
        initData();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (logoutCall != null) {
            logoutCall.cancel();
        }
        super.onDestroy();
    }
}
